package com.ynwt.jms;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.util.UUID;

/**
 * Created by huangying on 2017/4/27.
 */
@Component
public class QueueClient {

    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     *
     * 用request-response的方式发送一个请求（request），并监听结果（response）
     *
     * @param request 请求的参数
     * @param queueName queue名称
     * @param receiveTimeout 超时时间
     * @return
     * @throws JMSException
     */
    public String sendAndReceive(final String request, String queueName, long receiveTimeout) throws JMSException {

        String response = null;

        jmsTemplate.setReceiveTimeout(receiveTimeout);

        Destination queue = new ActiveMQQueue(queueName);

        Message message = jmsTemplate.sendAndReceive(queue, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {

                //新建一个结果返回通道，并监听这个通道
                Destination tempDestination = session.createTemporaryQueue();

                //设置发送的消息的内容
                TextMessage textMessage = session.createTextMessage();
                textMessage.setText(request);
                textMessage.setJMSReplyTo(tempDestination);

                String correlationId = String.valueOf(UUID.randomUUID());
                textMessage.setJMSCorrelationID(correlationId);

                return textMessage;
            }
        });

        //加上这个判断条件，如果server端出现异常，message为null
        if (message instanceof ActiveMQTextMessage) {
            ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
            response = textMessage.getText();
        }

        return response;
    }
}
